Scorecard = {
  HOURLY : '5',
  DAILY : '4',
  WEEKLY : '3',
  MONTHLY : '2',
  database : "atcustomer.servehttp.com:8888"
};
Utils = {};
var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept',
    'Oct', 'Nov', 'Dec' ];
var days = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
var dayForMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

$(document)
    .ready(function() {
      $('form').on('submit', function(event) {
        event.preventDefault();
        Scorecard.update(false);
      });
      setInterval(function() {
        if ($("#refresh").hasClass("active")) {
          Scorecard.update(true);
        }
      }, 5000);
      $('fieldset input,select').on('click focus change', function() {
        $('#refresh').removeClass('active');
      });
      $('#group_level')
          .on('change',
            function(event) {
              var currentdate = new Date();
              switch (event.target.value) {
              case Scorecard.HOURLY:
                var max = currentdate.getFullYear() + "-"
                    + ('0' + (currentdate.getMonth() + 1)).slice(-2) + "-"
                    + ('0' + currentdate.getDate()).slice(-2);
                $('#startkey')
                    .replaceWith('<input id="startkey" name="startkey" type="date" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey').hide();
                $('#endkey').val('');
                break;
              case Scorecard.DAILY:
                var max = currentdate.getFullYear() + "-"
                    + ('0' + (currentdate.getMonth() + 1)).slice(-2) + "-"
                    + ('0' + currentdate.getDate()).slice(-2);
                $('#startkey')
                    .replaceWith('<input id="startkey" name="startkey" type="date" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey')
                    .replaceWith('<input id="endkey" name="endkey" type="date" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey').show();
                break;
              case Scorecard.WEEKLY:
                var max = currentdate.getFullYear() + "-W"
                    + Utils.getWeekNumber(currentdate);
                $('#startkey')
                    .replaceWith('<input id="startkey" name="startkey" type="week" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey')
                    .replaceWith('<input id="endkey" name="endkey" type="week" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey').show();
                break;
              case Scorecard.MONTHLY:
                var max = currentdate.getFullYear() + "-"
                    + ('0' + (currentdate.getMonth() + 1)).slice(-2);
                $('#startkey')
                    .replaceWith('<input id="startkey" name="startkey" type="month" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey')
                    .replaceWith('<input id="endkey" name="endkey" type="month" value="'
                        + max + '" max="' + max + '"/>');
                $('#endkey').show();
                break;
              }
            });
    });

Utils.getWeekNumber = function(d) {
  d = new Date(d);
  d.setHours(0, 0, 0);
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  var yearStart = new Date(d.getFullYear(), 0, 1);
  var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
  return weekNo;
};

Utils.w2date = function(year, wn, dayNb) {
  var j10 = new Date(year, 0, 10, 12, 0, 0), j4 = new Date(year, 0, 4, 12, 0, 0), mon1 = j4
      .getTime()
      - j10.getDay() * 86400000;
  return new Date(mon1 + ((wn - 1) * 7 + dayNb) * 86400000);
};

Scorecard.update = function(replot) {
  var agency = $("#agency").val();
  var operation = $("#operation").val();
  var graph_type = $('#graph_type').val();
  var group_level = $('#group_level').val();
  var startkey = new Date($('#startkey').val());
  var endkey = new Date($('#endkey').val());
  if (!agency) {
    var warning = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;'
        + '</button><strong>Attenzione!</strong> Selezionare una filiale da monitorare.</div>';
    $('#container').prepend(warning);
    return;
  }
  switch (group_level) {
  case Scorecard.MONTHLY:
    endkey.setDate(dayForMonth[endkey.getMonth()]);
    break;
  case Scorecard.WEEKLY:
    var from = ($('#startkey').val()).split('-W');
    var to = ($('#endkey').val()).split('-W');
    startkey = new Date(Utils.w2date(from[0], from[1], 0));
    endkey = new Date(Utils.w2date(to[0], to[1], 6));
    break;
  case Scorecard.HOURLY:
    endkey = new Date(startkey.toDateString());
    break;
  }
  endkey.setHours(23);
  switch (graph_type) {
  case '1':
    Scorecard.typeBar(replot,
      startkey,
      endkey,
      agency,
      operation,
      graph_type,
      group_level);
    break;
  case '2':
    Scorecard.typeLine(replot,
      startkey,
      endkey,
      agency,
      operation,
      graph_type,
      group_level);
    break;
  case '3':
    Scorecard.typePie(replot,
      startkey,
      endkey,
      agency,
      operation,
      graph_type,
      group_level);
    break;
  }
};
Scorecard.typeBar = function(replot, startkey, endkey, agency, operation,
    graph_type, group_level) {
  if (!replot) {
    $('#row').empty();
  }
  // TODO enable for multiple
  // for ( var i = 0; i < agency.length; i++) {
  $
      .ajax(
      // 'http://' + Scorecard.database + '/' + agency[i] + '/_design/'
      'http://' + Scorecard.database + '/' + agency + '/_design/' + operation
          + '/_view/sum',
        {
          context : {
            // agency : agency[i]
            agency : agency
          },
          type : 'GET',
          dataType : 'json',
          data : {
            group_level : parseInt(group_level, 10) === 4 ? 3
                : parseInt(group_level, 10),
            startkey : JSON.stringify([ startkey.getFullYear(),
                startkey.getMonth() + 1, startkey.getDate(),
                startkey.getHours() ]),
            endkey : JSON.stringify([ endkey.getFullYear(),
                endkey.getMonth() + 1, endkey.getDate(), endkey.getHours() ])
          }
        })
      .done(function(data) {
        var ticks = [];
        var level_1 = [];
        var level_3 = [];
        var level_5 = [];
        var level_7 = [];
        if (data.rows.length === 0) {
          var warning = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;'
              + '</button><strong>Attenzione!</strong> Nessun valore presente per la filiale '
              + this.agency + '.</div>';
          $('#container').prepend(warning);
          return;
        } else {
          if (!replot) {
            var row_well = $('<div class="row well"></div>');
            var row_graph = $('<div id="graph_' + this.agency + '" ></div>');
            $('#row').append(row_well);
            $(row_well).append('<h2>' + this.agency + '</h2>');
            $(row_well).append(row_graph);
            $(row_well).append('<div id="table_' + this.agency + '" ></div>');
          } else {
            $('#table_' + this.agency).empty();
          }
          var table = $('<table class="table table-hover"><thead></thead>'
              + '<tbody></tbody><tfoot></tfoot></table>');
          $('#table_' + this.agency).append(table);
          var thead = $(table[0].tHead);
          var tbody = $(table[0].tBodies);
          thead.append("<th>");
          var level7_row = $('<tr>').appendTo(tbody).append("<th>Ottimo</th>");
          var level5_row = $('<tr>').appendTo(tbody).append("<th>Buono</th>");
          var level3_row = $('<tr>').appendTo(tbody).append("<th>Medio</th>");
          var level1_row = $('<tr>').appendTo(tbody).append("<th>Basso</th>");
          var week = [];
          $.each(data.rows, function(index, value) {
            var year = value.key[0];
            var month = value.key[1] - 1;
            var day = value.key[2];
            var tmpdate = null;
            switch (group_level) {
            case Scorecard.HOURLY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              tmpdate = new Date(year, month, day, value.key[3]);
              ticks.push('h ' + tmpdate.getHours());
              thead.append('<th>' + 'h ' + tmpdate.getHours() + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            case Scorecard.DAILY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              tmpdate = new Date(year, month, day);
              day = days[tmpdate.getDay()] + " " + tmpdate.getDate();
              ticks.push(day);
              thead.append('<th>' + day + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            case Scorecard.WEEKLY:
              tmpdate = new Date(year, month, day);
              if (Utils.getWeekNumber(tmpdate) in week) {
                week[Utils.getWeekNumber(tmpdate)] = {
                  "level_1" : week[Utils.getWeekNumber(tmpdate)]['level_1']
                      + value.value[0],
                  "level_3" : week[Utils.getWeekNumber(tmpdate)]['level_3']
                      + value.value[1],
                  "level_5" : week[Utils.getWeekNumber(tmpdate)]['level_5']
                      + value.value[2],
                  "level_7" : week[Utils.getWeekNumber(tmpdate)]['level_7']
                      + value.value[3]
                };
              } else {
                ticks.push(Utils.getWeekNumber(tmpdate));
                week[Utils.getWeekNumber(tmpdate)] = {
                  "level_1" : value.value[0],
                  "level_3" : value.value[1],
                  "level_5" : value.value[2],
                  "level_7" : value.value[3]
                };
              }
              break;
            case Scorecard.MONTHLY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              month = months[value.key[1] - 1] + ' ' + value.key[0];
              ticks.push(month);
              thead.append('<th>' + month + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            }
          });

          if (group_level === Scorecard.WEEKLY) {
            $.each(ticks, function(index, value) {
              level_1.push(week[value]['level_1']);
              level_3.push(week[value]['level_3']);
              level_5.push(week[value]['level_5']);
              level_7.push(week[value]['level_7']);
              thead.append('<th>' + value + '</th>');
              level7_row.append('<td>' + week[value]['level_7'] + '</td>');
              level5_row.append('<td>' + week[value]['level_5'] + '</td>');
              level3_row.append('<td>' + week[value]['level_3'] + '</td>');
              level1_row.append('<td>' + week[value]['level_1'] + '</td>');
            });
          }
          if (replot) {
            $('#graph_' + this.agency).data('jqplot').replot({
              data : [ level_1, level_3, level_5, level_7 ]
            });
          } else {
            $("#graph_" + this.agency).jqplot([ level_1, level_3, level_5,
                level_7 ],
              {
                animate : true,
                // animateReplot: true,
                seriesDefaults : {
                  renderer : $.jqplot.BarRenderer,
                  pointLabels : {
                    show : true,
                    formatString : '%.0f'
                  }
                },
                seriesColors : [ "#E6E6E6", "#49AFCD", "#47a4ff", "#006DCC" ],
                legend : {
                  show : true,
                  location : 'ne',
                  placement : 'outsideGrid',
                  labels : [ "basso", "medio", "buono", "ottimo" ]
                },
                axesDefaults : {
                  labelRenderer : $.jqplot.CanvasAxisLabelRenderer
                },
                axes : {
                  xaxis : {
                    label : 'Periodo',
                    renderer : $.jqplot.CategoryAxisRenderer,
                    ticks : ticks
                  },
                  yaxis : {
                    label : 'Soddisfazione',
                    tickOptions : {
                      show : false
                    }
                  }
                }
              });
          }
        }
      });
  // }
};

Scorecard.typeLine = function(replot, startkey, endkey, agency, operation,
    graph_type, group_level) {
  var totalVotes = [];
  var average = [];
  var agencies = [];
  var columnIndex = 0;
  // tooltip for highlight
  function tooltipContentEditor(str, seriesIndex, pointIndex, plot) {
    return agencies[seriesIndex] + " media " + average[seriesIndex][pointIndex]
        + " voti " + totalVotes[seriesIndex][pointIndex];
  }
  if (!replot) {
    $('#row').empty();
    var row_well = $('<div class="row well"></div>');
    $(row_well).append('<h2>Media</h2>');
    $(row_well).append('<div id="graph" ></div>');
    $(row_well).append('<div id="table" ></div>');
    $('#row').append(row_well);
    $('#graph').jqplot([ [ null ] ], {
      animate : true,
      animateReplot : true,
      canvasOverlay : {
        show : true,
        objects : [ {
          horizontalLine : {
            y : 2,
            lineWidth : 8,
            color : 'rgba(255, 0, 0,0.30)',
            shadow : false,
            showTooltip : true,
            tooltipFormatString : "Bassa soddisfazione"
          }
        }, {
          horizontalLine : {
            y : 4.0,
            lineWidth : 8,
            color : 'rgba(250, 250, 0,0.30)',
            shadow : false
          }
        }, {
          horizontalLine : {
            y : 6,
            lineWidth : 8,
            color : 'rgba(145, 213, 67,0.30)',
            shadow : false,
            showTooltip : true,
            tooltipFormatString : "Alta soddisfazione"
          }
        } ]
      },
      axesDefaults : {
        labelRenderer : $.jqplot.CanvasAxisLabelRenderer
      },
      highlighter : {
        show : true,
        bringSeriesToFront : true,
        tooltipLocation : 'n',
        tooltipOffset : 2,
        sizeAdjust : 8.5,
        tooltipContentEditor : tooltipContentEditor
      },
      axes : {
        xaxis : {
          label : 'Periodo',
          renderer : $.jqplot.CategoryAxisRenderer
        },
        yaxis : {
          label : 'Soddisfazione'
        }
      }
    });
  } else {
    $('#table').empty();
  }
  var table = $('<table class="table table-hover"><thead></thead>'
      + '<tbody></tbody><tfoot></tfoot></table>');
  $('#table').append(table);
  var thead = $(table[0].tHead);
  var tbody = $(table[0].tBodies);
  thead.append("<th>");
  array = [];
  // for ( var i = 0; i < agency.length; i++) {
  // average[i] = ([]);
  // totalVotes[i] = ([]);
  // array.push($.ajax('http://' + Scorecard.database + '/' + agency[i]
  // + '/_design/' + operation + '/_view/avg',
  // {
  // context : {
  // agency : agency[i],
  // serie : i
  // },
  // type : 'GET',
  // dataType : 'json',
  // data : {
  // group_level : parseInt(group_level, 10) === 4 ? 3 : parseInt(
  // group_level, 10),
  // startkey : JSON.stringify([ startkey.getFullYear(),
  // startkey.getMonth() + 1, startkey.getDate(),
  // startkey.getHours() ]),
  // endkey : JSON.stringify([ endkey.getFullYear(),
  // endkey.getMonth() + 1, endkey.getDate(), endkey.getHours() ])
  // }
  // }));
  // }
  average[0] = ([]);
  totalVotes[0] = ([]);
  array.push($.ajax('http://' + Scorecard.database + '/' + agency + '/_design/'
      + operation + '/_view/avg', {
    context : {
      agency : agency,
      serie : 0
    },
    type : 'GET',
    dataType : 'json',
    username : 'unipd',
    password : 'LawImmElt4',
    // headers : {'Authorization':'Basic dW5pcGQ6Y2VraW1HYW5uRWw3'},
    data : {
      group_level : parseInt(group_level, 10) === 4 ? 3 : parseInt(group_level,
        10),
      startkey : JSON.stringify([ startkey.getFullYear(),
          startkey.getMonth() + 1, startkey.getDate(), startkey.getHours() ]),
      endkey : JSON.stringify([ endkey.getFullYear(), endkey.getMonth() + 1,
          endkey.getDate(), endkey.getHours() ])
    }
  }));
  $.when
      .apply(this, array)
      .then(function() {
        var i = 0;
        if (arguments[1] == "success") { // filiale singola
          i = 2;
        }
        for (i; i < arguments.length; i++) {
          var newarg = [];
          var ticks, serieIndex, avg = null;
          if (!this.length) {// no array
            ticks = [];
            agencies[this.serie] = this.agency;
            serieIndex = this.serie;
            newarg[i] = arguments;
            if (newarg[i][0].rows.length === 0) {
              var warning = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;'
                  + '</button><strong>Attenzione!</strong> Nessun valore presente per la filiale '
                  + this.agency + '.</div>';
              $('#container').prepend(warning);
              continue;
            } else {
              avg = $('<tr>').appendTo(tbody).append('<th>' + this.agency
                  + '</th>');
            }
          } else {
            ticks = [];
            agencies[this[i].serie] = this[i].agency;
            serieIndex = this[i].serie;
            newarg = arguments;
            if (newarg[i][0].rows.length === 0) {
              var warning = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;'
                  + '</button><strong>Attenzione!</strong> Nessun valore presente per la filiale '
                  + this[i].agency + '.</div>';
              $('#container').prepend(warning);
              continue;
            } else {
              avg = $('<tr>').appendTo(tbody).append('<th>' + this[i].agency
                  + '</th>');
            }
          }
          var week = [];
          $.each(newarg[i][0].rows, function(index, value) {
            var year = value.key[0];
            var month = value.key[1] - 1;
            var day = value.key[2];
            var tmpdate = null;
            switch (group_level) {
            case Scorecard.HOURLY:
              average[serieIndex].push(Math
                  .round((value.value.sum / value.value.count) * 10) / 10);
              totalVotes[serieIndex].push(value.value.count);
              tmpdate = new Date(year, month, day, value.key[3]);
              ticks.push('h ' + tmpdate.getHours());
              if (columnIndex < newarg[i][0].rows.length) {
                thead.append('<th>' + 'h ' + tmpdate.getHours() + '</th>');
                columnIndex++;
              }
              avg.append('<td>'
                  + Math.round((value.value.sum / value.value.count) * 10) / 10
                  + '</td>');
              break;
            case Scorecard.DAILY:
              average[serieIndex].push(Math
                  .round((value.value.sum / value.value.count) * 10) / 10);
              totalVotes[serieIndex].push(value.value.count);
              tmpdate = new Date(year, month, day);
              day = days[tmpdate.getDay()] + " " + tmpdate.getDate();
              ticks.push(day);
              if (columnIndex < newarg[i][0].rows.length) {
                thead.append('<th>' + day + '</th>');
                columnIndex++;
              }
              avg.append('<td>'
                  + Math.round((value.value.sum / value.value.count) * 10) / 10
                  + '</td>');
              break;
            case Scorecard.WEEKLY:

              tmpdate = new Date(year, month, day);
              if (Utils.getWeekNumber(tmpdate) in week) {
                week[Utils.getWeekNumber(tmpdate)] = {
                  "sum" : week[Utils.getWeekNumber(tmpdate)]['sum']
                      + value.value.sum,
                  "value" : week[Utils.getWeekNumber(tmpdate)]['value']
                      + value.value.count,
                };
              } else {
                ticks.push(Utils.getWeekNumber(tmpdate));
                week[Utils.getWeekNumber(tmpdate)] = {
                  "sum" : value.value.sum,
                  "value" : value.value.count,
                };
              }
              break;
            case Scorecard.MONTHLY:
              average[serieIndex].push(Math
                  .round((value.value.sum / value.value.count) * 10) / 10);
              totalVotes[serieIndex].push(value.value.count);
              month = months[value.key[1] - 1] + ' ' + value.key[0];
              ticks.push(month);
              if (columnIndex < newarg[i][0].rows.length) {
                thead.append('<th>' + month + '</th>');
                columnIndex++;
              }
              avg.append('<td>'
                  + Math.round((value.value.sum / value.value.count) * 10) / 10
                  + '</td>');
              break;
            }
          });

          if (group_level === Scorecard.WEEKLY) {
            $
                .each(ticks,
                  function(index, value) {
                    average[serieIndex]
                        .push(Math
                            .round((week[value]['sum'] / week[value]['value']) * 10) / 10);
                    totalVotes[serieIndex].push(week[value]['value']);
                    if (columnIndex < newarg[i][0].rows.length) {
                      thead.append('<th>' + value + '</th>');
                      columnIndex++;
                    }
                    avg
                        .append('<td>'
                            + Math
                                .round((week[value]['sum'] / week[value]['value']) * 10)
                            / 10 + '</td>');

                  });
          }
          if (replot) {
            $('#graph').data("jqplot").data[serieIndex] = (average[serieIndex]);
            $('#graph').data("jqplot").replot({
              data : $('#graph').data("jqplot").data
            });
          } else {
            $('#graph').data("jqplot").data[serieIndex] = (average[serieIndex]);
            $('#graph').data("jqplot").replot($('#graph').data("jqplot").data);
            $('#graph').data("jqplot").axes.xaxis.ticks = ticks;
            $('#graph').data("jqplot").replot({
              resetAxes : {
                yaxis : true,
                xaxis : true
              }
            });
          }
        }
      });
};

Scorecard.typePie = function(replot, startkey, endkey, agency, operation,
    graph_type, group_level) {
  if (!replot)
    $('#row').empty();
  // for ( var i = 0; i < agency.length; i++) {
  $
      .ajax(
      // 'http://' + Scorecard.database + '/' + agency[i] + '/_design/'
      'http://' + Scorecard.database + '/' + agency + '/_design/' + operation
          + '/_view/sum',
        {
          context : {
            // agency : agency[i]
            agency : agency
          },
          type : 'GET',
          dataType : 'json',
          username : 'unipd',
          password : 'LawImmElt4',
          // headers : {'Authorization':'Basic dW5pcGQ6Y2VraW1HYW5uRWw3'},
          data : {
            group_level : parseInt(group_level, 10) === 4 ? 3
                : parseInt(group_level, 10),
            startkey : JSON.stringify([ startkey.getFullYear(),
                startkey.getMonth() + 1, startkey.getDate(),
                startkey.getHours() ]),
            endkey : JSON.stringify([ endkey.getFullYear(),
                endkey.getMonth() + 1, endkey.getDate(), endkey.getHours() ])
          }
        })
      .done(function(data) {
        var ticks = [];
        var level_1 = [];
        var level_3 = [];
        var level_5 = [];
        var level_7 = [];
        if (data.rows.length === 0) {
          var warning = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;'
              + '</button><strong>Attenzione!</strong> Nessun valore presente per la filiale '
              + this.agency + '.</div>';
          $('#container').prepend(warning);
        } else {
          if (!replot) {
            var row_well = $('<div class="row well"></div>');
            var row_graph = $('<div id="graph_' + this.agency + '" ></div>');
            $('#row').append(row_well);
            $(row_well).append('<h2>' + this.agency + '</h2>');
            $(row_well).append(row_graph);
            $(row_well).append('<div id="table_' + this.agency + '" ></div>');
          } else {
            $('#table_' + this.agency).empty();
          }
          var table = $('<table class="table table-hover"><thead></thead>'
              + '<tbody></tbody>' + '<tfoot></tfoot></table>');
          $('#table_' + this.agency).append(table);
          var thead = $(table[0].tHead);
          var tbody = $(table[0].tBodies);
          thead.append("<th>");
          var level7_row = $('<tr>').appendTo(tbody).append("<th>Ottimo</th>");
          var level5_row = $('<tr>').appendTo(tbody).append("<th>Buono</th>");
          var level3_row = $('<tr>').appendTo(tbody).append("<th>Medio</th>");
          var level1_row = $('<tr>').appendTo(tbody).append("<th>Basso</th>");
          var week = [];
          $.each(data.rows, function(index, value) {
            var year = value.key[0];
            var month = value.key[1] - 1;
            var day = value.key[2];
            var tmpdate = null;
            switch (group_level) {
            case Scorecard.HOURLY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              tmpdate = new Date(year, month, day, value.key[3]);
              ticks.push('h ' + tmpdate.getHours());
              thead.append('<th>' + 'h ' + tmpdate.getHours() + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            case Scorecard.DAILY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              tmpdate = new Date(year, month, day);
              day = days[tmpdate.getDay()] + " " + tmpdate.getDate();
              ticks.push(day);
              thead.append('<th>' + day + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            case Scorecard.WEEKLY:
              tmpdate = new Date(year, month, day);
              if (Utils.getWeekNumber(tmpdate) in week) {
                week[Utils.getWeekNumber(tmpdate)] = {
                  "level_1" : week[Utils.getWeekNumber(tmpdate)]['level_1']
                      + value.value[0],
                  "level_3" : week[Utils.getWeekNumber(tmpdate)]['level_3']
                      + value.value[1],
                  "level_5" : week[Utils.getWeekNumber(tmpdate)]['level_5']
                      + value.value[2],
                  "level_7" : week[Utils.getWeekNumber(tmpdate)]['level_7']
                      + value.value[3]
                };
              } else {
                ticks.push(Utils.getWeekNumber(tmpdate));
                week[Utils.getWeekNumber(tmpdate)] = {
                  "level_1" : value.value[0],
                  "level_3" : value.value[1],
                  "level_5" : value.value[2],
                  "level_7" : value.value[3]
                };
              }
              break;
            case Scorecard.MONTHLY:
              level_1.push(value.value[0]);
              level_3.push(value.value[1]);
              level_5.push(value.value[2]);
              level_7.push(value.value[3]);
              month = months[value.key[1] - 1] + ' ' + value.key[0];
              ticks.push(month);
              thead.append('<th>' + month + '</th>');
              level7_row.append('<td>' + value.value[3] + '</td>');
              level5_row.append('<td>' + value.value[2] + '</td>');
              level3_row.append('<td>' + value.value[1] + '</td>');
              level1_row.append('<td>' + value.value[0] + '</td>');
              break;
            }
          });

          if (group_level === Scorecard.WEEKLY) {
            $.each(ticks, function(index, value) {
              level_1.push(week[value]['level_1']);
              level_3.push(week[value]['level_3']);
              level_5.push(week[value]['level_5']);
              level_7.push(week[value]['level_7']);
              thead.append('<th>' + value + '</th>');
              level7_row.append('<td>' + week[value]['level_7'] + '</td>');
              level5_row.append('<td>' + week[value]['level_5'] + '</td>');
              level3_row.append('<td>' + week[value]['level_3'] + '</td>');
              level1_row.append('<td>' + week[value]['level_1'] + '</td>');
            });
          }
          var sum_1 = 0;
          var sum_3 = 0;
          var sum_5 = 0;
          var sum_7 = 0;
          for ( var i = 0; i < level_1.length; i++) {
            sum_1 += level_1[i];
            sum_3 += level_3[i];
            sum_5 += level_5[i];
            sum_7 += level_7[i];
          }
          if (replot) {
            $('#graph_' + this.agency).data('jqplot').replot({
              data : [ [ [ 'Basso', sum_1 ], [ 'Medio', sum_3 ],
                  [ 'Buono', sum_5 ], [ 'Ottimo', sum_7 ] ] ]
            });
          } else {
            $("#graph_" + this.agency)
                .jqplot([ [ [ 'Basso', sum_1 ], [ 'Medio', sum_3 ],
                    [ 'Buono', sum_5 ], [ 'Ottimo', sum_7 ] ] ],
                  {
                    seriesDefaults : {
                      renderer : jQuery.jqplot.PieRenderer,
                      rendererOptions : {
                        showDataLabels : true,
                        shadowOffset : 2,
                        dataLabelPositionFactor : 1.05,
                        startAngle : 35,
                        sliceMargin : 3
                      },
                      pointLabels : {
                        show : true
                      }
                    },
                    legend : {
                      show : true,
                      location : 'e'
                    },
                    seriesColors : [ "#E6E6E6", "#49AFCD", "#47a4ff", "#006DCC" ]
                  });
          }
        }
      });
  // }
};